package com.leetcode.partition4;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;

/**
 * @author `RKC`
 * @date 2022/1/14 19:03
 */
public class LC373查找和最小的K对数字 {

    private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    private static final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        String[] s = reader.readLine().split("\\s+");
        int[] nums1 = new int[s.length];
        for (int i = 0; i < s.length; i++) nums1[i] = Integer.parseInt(s[i]);
        s = reader.readLine().split("\\s+");
        int[] nums2 = new int[s.length];
        for (int i = 0; i < s.length; i++) nums2[i] = Integer.parseInt(s[i]);
        int k = Integer.parseInt(reader.readLine());
        List<List<Integer>> ans = kSmallestPairs(nums1, nums2, k);
        for (List<Integer> item : ans) {
            writer.write(item.get(0) + " " + item.get(1) + "\n");
        }
        writer.flush();
    }

    public static List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
        int n = nums1.length, m = nums2.length;
        List<List<Integer>> answer = new ArrayList<>(k);
        PriorityQueue<int[]> heap = new PriorityQueue<>((o1, o2) -> Integer.compare(nums1[o1[0]] + nums2[o1[1]], nums1[o2[0]] + nums2[o2[1]]));
        //将nums1的索引和nums2的索引放入堆中，初始化时nums2始终为第一位
        for (int i = 0; i < Math.min(n, k); i++) heap.add(new int[]{i, 0});
        while (k-- > 0 && !heap.isEmpty()) {
            int[] pair = heap.poll();
            answer.add(Arrays.asList(nums1[pair[0]], nums2[pair[1]]));
            if (pair[1] + 1 < m) heap.add(new int[]{pair[0], pair[1] + 1});
        }
        return answer;
    }
}
